#include "GameClient.h"

GameClient::GameClient(boost::asio::io_service& io_service, tcp::endpoint& endpoint, Player& login)
{
        connect(io_service,endpoint,login);
}

GameClient::GameClient()
{

}

Player& GameClient::get_login()
{
  return m_login;
}


void GameClient::connect(boost::asio::io_service& io_service,tcp::endpoint& endpoint,Player& login){
    m_io_service = &io_service;
    m_tcp_connection = (connection_ptr(new TCPConnection(*m_io_service)));
    m_login = login;
    // Connection au serveur
    tcp::socket& sock = m_tcp_connection->socket();
    sock.async_connect(endpoint,
            boost::bind(&GameClient::handle_connect, this,
            boost::asio::placeholders::error)
            );

}

// Close the connection
void GameClient::close()
{
        (*m_io_service).post(boost::bind(&GameClient::do_close, this));
}

void GameClient::handle_connect(const boost::system::error_code& error)
{
	if (!error)
	{
                GameMessage e;

		m_tcp_connection->async_read(m_message_read,
                        boost::bind(&GameClient::handle_read, this,
			boost::asio::placeholders::error)
			);
                e.m_type = GameMessage::PERSON_CONNECTED;
                e.m_login = this->m_login;
                m_tcp_connection->async_write(e,
                        boost::bind(&GameClient::handle_write, this,
                        boost::asio::placeholders::error)
                        );
	}
}


void GameClient::handle_read(const boost::system::error_code& error)
{
	if (!error)
	{
		notify(m_message_read);

		//m_message_read.reset();
		// On rcoute
		m_tcp_connection->async_read(m_message_read,
                        boost::bind(&GameClient::handle_read, this,
			boost::asio::placeholders::error)
			);

	}
	else
	{
		do_close();
	}
}

void GameClient::write(const std::string& msg)
{
        GameMessage e;
        e.m_type = GameMessage::NEW_MSG;
	e.m_login = m_login;
	e.m_message = msg;

	write(e);
}

void GameClient::write(GameMessage& e)
{
		m_tcp_connection->async_write(e,
                        boost::bind(&GameClient::handle_write, this,
			boost::asio::placeholders::error)
			);
}

void GameClient::handle_write(const boost::system::error_code& error)
{
	if (error)
	{
		do_close();
	}
}


void GameClient::do_close()
{
	m_tcp_connection->socket().close();
}
